import React, {Component} from 'react';
import {StyleSheet, Text, View,Image,
 TouchableOpacity,FlatList
} from 'react-native';
import Toast, {DURATION} from 'react-native-easy-toast'
import Picker from 'react-native-picker';
import RefreshListView, {RefreshState} from 'react-native-refresh-list-view';
import {createDateData,addByTransDate,reduceByTransDate,getCurrentDate} from '../../common/common'
import BASEURL from '../../api/api'
import Item from './Item'
import SearchView from '../../common/SearchView'
import Loading from '../../common/Loading'
import NoData from '../../common/NoData'
var noMore = false;
var pageNo = 1;
var pageSize = 10;
export default class History extends Component{
  constructor(props){
    super(props);
    let time = getCurrentDate()
    this.state = ({
      loading:true,
      historyList:[],
      hyName:'',
      isHistory:false,
      date:time,
    })
    //console.log(this.props)
  }
  componentWillMount(){
    this.getHistoryList()
  }
  onHeaderRefresh = () => {
  }
  onFooterRefresh = () => {
  	pageNo++;
  	this.getHistoryList();
    this.setState({refreshState: RefreshState.FooterRefreshing});
  }
  _openDatePicker(){
    console.log(111)
    var year = ''
    var month = ''
    var day = ''
    var dateStr = this.state.date
    year = dateStr.substring(0,4)
    month = parseInt(dateStr.substring(5,7))
    day = parseInt(dateStr.substring(8,10))
    Picker.init({
      pickerTitleText:'时间选择',
      pickerCancelBtnText:'取消',
      pickerConfirmBtnText:'确定',
      selectedValue:[year+'年',month+'月',day+'日'],
      pickerBg:[255,255,255,1],
      pickerData: createDateData(),
      pickerFontColor: [33, 33 ,33, 1],
      onPickerConfirm: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
          var year = pickedValue[0].substring(0,pickedValue[0].length-1)
          var month = pickedValue[1].substring(0,pickedValue[1].length-1)
          month = month.padStart(2,'0')
          var day = pickedValue[2].substring(0,pickedValue[2].length-1)
          day = day.padStart(2,'0')
          let str = year+'-'+month+'-'+day
          this.setState({
            date:str,
            historyList:[],
          })
          pageNo = 1
          setTimeout(()=>{
            this.getHistoryList()
          },50)
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      }
    });
    Picker.show();
  }
  //获取 历史监测数据
  getHistoryList(){
    fetch(BASEURL+'getFlowListDayAreaCode?areaCode='+this.props.areaCode
      +'&seachTime='+this.state.date+'&hyName='+this.state.hyName
      +'&pageNo='+pageNo+'&pageSize='+pageSize)
    .then(res=>res.json())
    .then(result=>{
      //console.log('res',result)
      if(result.falg){
        if(result.flowList.length<pageSize){
          noMore = true
          this.setState({
            historyList:this.state.historyList.concat(result.flowList),
            loading:false,
            refreshState: RefreshState.NoMoreData,
          })
        } else {
          this.setState({
            historyList:this.state.historyList.concat(result.flowList),
            loading:false,
            refreshState: RefreshState.Idle,
          })
        }
      } else {
        this.setState({
          loading:false,
          refreshState:RefreshState.Idle,
          msg:result.message,
        })
      }
    })
  }
  _lastDay(type){
    var newDate = ''
    if(type == 1){
      let currDate = getCurrentDate()
      if(this.state.date >= currDate){
        this.refs.toast.show('不能选择当前日期之后的日期');
        return
      } else {
        newDate = addByTransDate(this.state.date,1)
      }
      
    } else {
      newDate = reduceByTransDate(this.state.date,1)
    }
    this.setState({
      date:newDate,
      loading:true,
    })
    setTimeout(()=>{
      this.getHistoryList(1)
    },50)
  }
  searchFlowList(value){
    // console.log('value',value)
    this.setState({
      hyName:value,
      historyList:[],
    })
    //历史监测搜索
    setTimeout(()=>{
      this.getHistoryList()
    },50)
    
  }
  _separator = () => {
    return <View style={{height:10,backgroundColor:'#f0f0f0'}}/>;
  }
  _keyExtractor = (item, index) => index.toString();
  _renderItem = ({item,index}) =>{
    return(
      <Item item={item} isHistory={true} navigation={this.props.navigation}/>
    )
  }
  render(){
    var nodata = (this.state.historyList.length==0 && pageNo==1)
    //console.log('nodata',nodata)
    return(
      <View style={{flex:1}} >
          <View style={styles.headerViewStyle}>
            <TouchableOpacity activeOpacity={0.5} style={styles.button} onPress={()=>this._lastDay(-1)}>
              <Image source={require('../../images/date-pre.png')} />
              <Text style={{marginLeft:8}}>前一天</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={()=>{this._openDatePicker()}}>
              <Text>{this.state.date}</Text>
            </TouchableOpacity>
            <TouchableOpacity activeOpacity={0.5} style={styles.button} onPress={()=>this._lastDay(1)}>
              <Text style={{marginRight:8}}>后一天</Text>
              <Image source={require('../../images/date-next.png')} />
            </TouchableOpacity>
          </View>
          <SearchView  placeholder='输入电站名' search={(val)=>this.searchFlowList(val)}/>
          {this.state.loading?<Loading/>:(nodata?<NoData msg={this.state.msg}/>:
            <RefreshListView
              style={{flex:1}}
              data={this.state.historyList}
              keyExtractor={this._keyExtractor}
              renderItem={this._renderItem}
              ItemSeparatorComponent={this._separator}
              refreshState={this.state.refreshState}
              onHeaderRefresh={this.onHeaderRefresh}
              onFooterRefresh={this.onFooterRefresh}
              // 可选
              footerRefreshingText= '数据加载中...'
              footerFailureText = '--数据加载失败--'
              footerNoMoreDataText= '--没有更多了--'
            />)
            }
            <Toast ref="toast" position='bottom' positionValue={200} />
        </View>
    )
  }
}
const styles = StyleSheet.create({
  headerViewStyle:{
    flexDirection:'row',
    alignItems:'center',
    justifyContent:'space-between',
    paddingTop:10,
    paddingBottom:10,
    paddingLeft:20,
    paddingRight:20,
    backgroundColor:'white',
  },
  button:{
    flexDirection:'row',
    alignItems:'center',
  },
})